#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         RemoveAssessmentFromRepository.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  This file defines the RemoveAssessmentFromRepository class,
#               to remove an assessment to one or more repositories.
#
#               NOTE: Does not remove the assessment for it's current
#               repository
#
# See Also:     Action, Event
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Action import Action, ActionInfo
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## Private Functions (global)

def getRepositories(context):
    """
        Returns a [(name,identity)] of repositories within the model
        (using the context to look it up)
    """

    #get our model
    model = context.getParentByInstanceOf("Model")
    
    #return the list of available repositories in the model (including the user)
    return [('(current user)', 'user')] + [(repository.getTitleOrId(),repository.getIdentity()) for repository in model.getRepositories()]

#####################################################################
## RemoveAssessmentFromRepositoryInfo Class Definition
class RemoveAssessmentFromRepositoryInfo(ActionInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """
    
    #---------------------------------------------------------------#
    
    def getClassName(self):
        """
            Returns the name of the class for which 
            we are providing information.
        """
        return "RemoveAssessmentFromRepository"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """
    
        return "Remove Assessment From Repository"
        
    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.  
        """
        
        return "removeAssessment"
        
    #---------------------------------------------------------------#
    
    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """
        
        return ImageFile('skins/RemoveAssessmentFromRepository_icon.gif', globals())
   
    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register 
            class specific properties using the PropertyReflection interface.
            
            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered
            
            NOTE: This method is called before ClassInfo.onAfterStartup()            
        """

        #initialise the super-class properties for reflection
        ActionInfo.onConfigureProperties(self)
        
        #add the 'repositories' property
        #(the property represents a repositories to which the assessment will be added)
        self.addPropertyDefinition(PropertyDefinition(identity="repositories", displayName="Repositories...", description="The repositories from which the assessment should be removed.", defaultValue=[], propertyType=pt_STRING, propertyFormat=pf_NATIVE, propertyStructure=ps_LIST, hasEnumeratedValues=true, enumeratedValuesFunction=getRepositories))

    #---------------------------------------------------------------#

#####################################################################
## RemoveAssessmentFromRepository Action Class Definition
class RemoveAssessmentFromRepository(Action):
    """
        A class to represent a simple folder that may contain Elements
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = RemoveAssessmentFromRepositoryInfo()
    
    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the Folder"        

        Action.__init__(self, id, identity)
                
        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object 
            has been loaded into memory.  
            
            This is useful for performing backwards compatibility
        """        
        
        #perform default processing
        Action.onAfterInstanciation(self)
        
    #---------------------------------------------------------------#

    def getSelectedRespositoryIdentities(self):
        """
            Returns a list of the repository (identities) to which
            assessments should be added when this action is executed
        """
        
        return self.repositories
    
    #---------------------------------------------------------------#
    
    def execute(self, assessment, user = None, previousActionSuccess = true):
        """
           Removes the assessment from the repositories specified by this
           action
        """            

        #assume event handled correctly
        actionSuccess = true   

        #let's grab the model so we can do some work
        model = assessment.getModel()
        
        #get the assessment storage service (so we can add the assessment to the specified repositories)
        assessmentStorageService = model.getAssessmentStorageService()
        
        #add the assessment to the current user if required
        if 'user' in self.getSelectedRespositoryIdentities() and user is not None:
            #add the assessment to the user 
            assessmentStorageService.removeAssessmentFromRepository(assessment, user.getIdentity())            
        
        #add the assessment to the specified repositories
        for repository in model.getRepositories():
        
            #is the current repository (id) in the set for this action?
            if repository.getIdentity() in self.getSelectedRespositoryIdentities():

                #handle the 'onBeforeAssessmentLeaves' event for the repository
                if repository.isEventEnabled("onBeforeAssessmentLeaves"):
                    repository.getEnabledEvent("onBeforeAssessmentLeaves").execute(assessment, user)
            
                #add the assessment to the current repository
                assessmentStorageService.removeAssessmentFromRepository(assessment, repository.getIdentity())
        
        #return the result of the action      
        return actionSuccess
        
    #---------------------------------------------------------------#

#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(RemoveAssessmentFromRepository)

#####################################################################